package com.wclass.controller.app;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Maps;
import com.wclass.common.ReturnObject;
import com.wclass.entity.*;
import com.wclass.interceptor.BaseContextHandler;
import com.wclass.interceptor.IgnoreAuth;
import com.wclass.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 团队介绍-图片 前端控制器
 * </p>
 *
 * @author SEN
 * @since 2019-02-14
 */
@Api(description = "消息管理")
@RestController
@RequestMapping("/message")
public class MsgController {
    @Autowired
    private IBaseNoticeService iBaseNoticeService;
    @Autowired
    private IBaseFocusService iBaseFocusService;
    @Autowired
    private IPostsLikeService iPostsLikeService;
    @Autowired
    private IPostsReplyService iPostsReplyService;
    @Autowired
    private IBaseAppUserService iBaseAppUserService;
    @Autowired
    private IBaseOrganService iBaseOrganService;
    @Autowired
    private IBaseTeamUserService iBaseTeamUserService;

    @ApiOperation("新消息统计")
    @RequestMapping(value = "/getStatistics", method = RequestMethod.POST)
    public ReturnObject<Object> getStatistics(@ApiParam("类型 1 学生 2老师 3平台") @RequestParam Integer type) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("comments", iPostsReplyService.selectUnreadPostsReplyCount(BaseContextHandler.getUserID()));//评论数
        map.put("likes", iPostsLikeService.selectCount(new EntityWrapper<PostsLike>().eq("info.is_new", 0).eq("posts.user_id", BaseContextHandler.getUserID())));//点赞数
        map.put("chats", 0);//私聊数
        map.put("fans", iBaseFocusService.selectCount(new EntityWrapper<BaseFocus>().eq("focus_user_id", BaseContextHandler.getUserID()).eq("is_new", 0).eq("state", 0)));//粉丝数
        //系统消息未读数
        EntityWrapper<BaseNotice> ew = new EntityWrapper<>();
        if (type == 1) {
            ew.in("type", "1,3").notLike("read_users", BaseContextHandler.getUserID().toString());
        }
        if (type == 2) {
            ew.in("type", "2,3").notLike("read_users", BaseContextHandler.getUserID().toString());
        }
        if (BaseContextHandler.getUserID() != null) {
            ew.orNew().eq("type", 4).eq("to_user_id", BaseContextHandler.getUserID()).notLike("read_users", BaseContextHandler.getUserID().toString());
        }
        map.put("notices", iBaseNoticeService.selectCount(ew));
        return new ReturnObject<>(0, "获取成功", map);
    }

    @ApiOperation("获取系统消息分页")
    @RequestMapping(value = "/getNoticePage", method = RequestMethod.POST)
    public ReturnObject<List<BaseNotice>> getNoticePage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                        @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                        @ApiParam("类型 1 学生 2老师") @RequestParam Integer type) {
        EntityWrapper<BaseNotice> ew = new EntityWrapper<>();
        if (type == 1) {
            ew.in("type", "1,3");
        } else if (type == 2) {
            ew.in("type", "2,3");
        }
        ew.orNew().eq("type", 4).eq("to_user_id", BaseContextHandler.getUserID());
        ew.orderBy("crt_time");
        Page<BaseNotice> obj = iBaseNoticeService.selectPage(new Page<>(offset, limit), ew);
        for (BaseNotice notice : obj.getRecords()) {
            if (notice.getReadUsers() != null && notice.getReadUsers().contains(BaseContextHandler.getUserID().toString())) {
                notice.setReadState(1);
            } else {
                notice.setReadState(0);
            }

            if (notice.getFromUserId() == 0)
                notice.setFromUserName("官方");
            else
                notice.setFromUserName(iBaseAppUserService.selectById(notice.getFromUserId()).getNickName());
        }

        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    @ApiOperation("获取系统消息详情")
    @RequestMapping(value = "/getNoticeInfo", method = RequestMethod.POST)
    public ReturnObject<BaseNotice> getNoticeInfo(@ApiParam("Id") @RequestParam Long id) {
        BaseNotice info = iBaseNoticeService.selectById(id);
        if (info.getFromUserId() == 0)
            info.setFromUserName("官方");
        else
            info.setFromUserName(iBaseAppUserService.selectById(info.getFromUserId()).getNickName());

        String readUsers = info.getReadUsers();
        Boolean isContain = false;
        if (readUsers != null)
            isContain = readUsers.contains(BaseContextHandler.getUserID() + "");

        if (!isContain) {
            if (readUsers == null) {
                readUsers = BaseContextHandler.getUserID() + "";
            } else {
                readUsers = readUsers + "," + BaseContextHandler.getUserID();
            }
            info.setReadUsers(readUsers);
            iBaseNoticeService.updateById(info);
        }

        return new ReturnObject<>(0, "获取成功", info);
    }

    @ApiOperation("回复系统邀请消息")
    @RequestMapping(value = "/replyNotice", method = RequestMethod.POST)
    public ReturnObject<Object> replyNotice(@ApiParam("Id") @RequestParam Long id,
                                            @ApiParam("回复类型，1：同意，2：拒绝") @RequestParam(defaultValue = "1") Integer type){
        BaseNotice info = iBaseNoticeService.selectById(id);

        String ret = "";
        if (info.getMsgType() == 1) {
            BaseAppUser loginUser = iBaseAppUserService.selectById(BaseContextHandler.getUserID());
            BaseAppUser teacher = iBaseAppUserService.selectById(info.getFromUserId());
            BaseOrgan organ = iBaseOrganService.selectById(teacher.getInstitutionId());

            BaseNotice notice = new BaseNotice();
            notice.setCrtTime(new Date());
            notice.setType(4);
            if (type == 1) {
                if (organ.getType() == 1) {
                    notice.setTitle("成功邀请ID：" + loginUser.getId() + "（" + loginUser.getNickName() + "）加入" + organ.getName());
                    notice.setContent(loginUser.getId() + "（" + loginUser.getNickName() + "）已成功加入" + organ.getName());

                    ret = "您已成功加入" + organ.getName();
                } else {
                    notice.setTitle("成功邀请ID：" + loginUser.getId() + "（" + loginUser.getNickName() + "）加入团队");
                    notice.setContent(loginUser.getId() + "（" + loginUser.getNickName() + "）已成功加入团队");

                    ret = "您已成功加入团队";
                }

                //用户机构邀请状态修改
                loginUser.setType(1);
                loginUser.setInstitutionInviteState(2);
                iBaseAppUserService.updateById(loginUser);

                //机构、团队成员插入
                BaseTeamUser teamUser = new BaseTeamUser();
                teamUser.setCrtTime(new Date());
                teamUser.setTeamId(organ.getId());
                teamUser.setUserId(loginUser.getId());
                iBaseTeamUserService.insert(teamUser);
            } else {
                if (organ.getType() == 1) {
                    notice.setTitle("ID：" + loginUser.getId() + "（" + loginUser.getNickName() + "）拒绝加入" + organ.getName());
                    notice.setContent(loginUser.getId() + "（" + loginUser.getNickName() + "）已拒绝加入" + organ.getName());

                    ret = "您已拒绝加入" + organ.getName();
                } else {
                    notice.setTitle("ID：" + loginUser.getId() + "（" + loginUser.getNickName() + "）拒绝加入团队");
                    notice.setContent(loginUser.getId() + "（" + loginUser.getNickName() + "）已拒绝加入团队");

                    ret = "您已拒绝加入团队";
                }

                loginUser.setInstitutionInviteState(3);
                iBaseAppUserService.updateById(loginUser);
            }
            notice.setState(0);
            notice.setFromUserId(info.getToUserId());
            notice.setToUserId(info.getFromUserId());
            notice.setMsgType(2);
            iBaseNoticeService.insert(notice);
        }
        info.setReplyState(1);
        iBaseNoticeService.updateById(info);

        return new ReturnObject(0, "操作成功", ret);
    }


}

